// miniprogram/pages/expenses/Index.js
var util = require('../util.js')
var plugin = requirePlugin("WechatSI")
let manager = plugin.getRecordRecognitionManager()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imagesList: [],
    fileIDs: [], //上传云存储后的返回值
    input1: 0,
    input2: 0,
    input3: 0,
    input4: 0,
    input5: 0,
    count: 0,
    date: '',
    fdate: '',
    all: {},
    btnname: "确认提交",
    btnstate: false,
    Temp: true,
    tlist: [],
    switch: false,
    latitude: '',//坐标
    longitude: '',//坐标
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.GetList();
    this.GetSet();
    var now = new Date().Format("yyyy-MM-dd");
    var chday = this.Checkday(now)
    if (chday) {
      this.setData({
        date: now,
        fdate: now
      })
    }
    this.getLocation();
  },

  endStreamRecord: function () {
    wx.hideToast(),
      manager.stop()
  },
  initRecord: function () {
    //有新的识别内容返回，则会调用此事件
    manager.onRecognize = (res) => {
      let text = res.result
      this.setData({
        currentText: text,
      })
    }
    // 识别结束事件
    manager.onStop = (res) => {
      let text = res.result
      if (text == '') {
        // 用户没有说话，可以做一下提示处理...
        return
      }
      this.setData({
        currentText: text,
      })
      // 得到完整识别内容就可以去翻译了
      this.translateTextAction()
    }
  },
  translateTextAction: function () { },

  cal: function () {
    var count = 0;
    var all = this.data.all;
    for (var i in all) {
      count += Number(all[i]);
    }
    this.setData({
      count: count.toFixed(2)
    });
    //console.log(this.data.count, count, all);
  },

  inputB: function (e) {
    var all = this.data.all;
    var iname = e.target.dataset.iname;
    all[iname] = (e.detail.value * 1).toFixed(2);
    this.setData({
      all: all,
      [iname]: (e.detail.value * 1).toFixed(2)
    });
    this.cal();
  },
  switchCheck(e) {
    this.setData({ switch: e.detail.value })
  },
  wselect(e) {
    var that = this, data_json = '{"K_W_Expenses":{"id":' + this.data.tlist[e.detail.value].id + ',"Openid":"' + getApp().globalData.openid + '","@column":"Memo"}}'
    console.log(data_json);
    wx.cloud.callFunction({
      name: 'Get_fun',
      data: {
        data: data_json
      },
      success: res => {
        console.log(res.result);
        let obj = JSON.parse(res.result)["K_W_Expenses"];
        that.setData({ currentText: obj.Memo });
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err);
        wx.showToast({
          icon: 'none',
          title: '调用失败',
        })
      }
    })
  },
  bindDateChange: function (e) {
    var chday = this.Checkday(e.detail.value)
    if (chday) {
      this.setData({
        date: e.detail.value
      })
    }
  },

  bindfDateChange: function (e) {
    this.setData({
      fdate: e.detail.value
    })
  },

  //图片
  chooseImage(e) {
    var that = this
    var imgs = that.data.imagesList;
    if (imgs.length > 4) {
      wx.showToast({
        icon: 'none',
        title: '减少资源浪费，最多只能上传3张图片',
      })
      return false;
    };
    wx.chooseImage({
      count: (5 - imgs.length), // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths = imgs.concat(res.tempFilePaths);
        that.setData({
          imagesList: tempFilePaths
        })

      }
    })
  },
  previewImage: function (e) {
    var current = e.currentTarget.dataset.id;
    wx.previewImage({
      current: current, // 当前显示图片的http链接  
      urls: this.data.imagesList // 需要预览的图片http链接列表  
    })
  },
  deleteImg: function (e) {
    var imgs = this.data.imagesList;
    var index = e.currentTarget.dataset.idx;
    imgs.splice(index, 1);
    this.setData({
      imagesList: imgs
    });
  },
  formSubmit: function (e) {
    var that = this;
    var Template = this.data.switch;
    var data = this.data.date;
    console.log(data);
    if (this.data.longitude == '' && this.data.latitude == '') {
      wx.showToast({
        icon: 'none',
        title: '请打开定位！',
      });
      this.getLocation();
      return false
    }
    if (data == '') {
      wx.showToast({
        icon: 'none',
        title: '请选择出差日期！',
      });
      return;
    }  
    let {
      destination, //目的地
      from, //出发地
      work_log, //工作事项
      fare, //车费
      station, //驻地
      stay, //住宿
      meals, //餐费
      other, //其他
      memo_log,//备注内容
    } = e.detail.value;
    console.log(other);
    if (!destination || !from || !work_log) {
      wx.showToast({
        icon: 'none',
        title: '请输入相关信息！',
      });
      return;
    }

    var Template = this.data.switch;
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    var ex = timestamp + 10;    
    if (ex - wx.getStorageSync('ex') < 0) {
      wx.showToast({
        icon: 'none',
        title: '请稍等10秒后再提交！',
      });
      return false;
    }
    wx.setStorageSync('ex', ex+10)
    wx.showLoading(); //展示加载
    this.setData({
      btnname: "提交中",
      btnstate: true
    })
    let promiseArr = [];
    var imgs = this.data.imagesList,
      guid = util.uuid().replace(/-/g, '');
    if (imgs.length > 0) {
      for (let i = 0; i < imgs.length; i++) {
        promiseArr.push(new Promise((reslove, reject) => {
          //------------------------------
          let filePath = this.data.imagesList[i];
          let fileName = guid + "-" + i + filePath.match(/\.[^.]+?$/)[0]
          let cloudPath = "img_ex/" + fileName;
          wx.cloud.uploadFile({
            cloudPath, //云存储图片名字
            filePath, //临时路径
            success: res => {
              console.log('[上传图片] 成功：', res)
              this.setData({
                fileIDs: this.data.fileIDs.concat(fileName)
              });
              let data = '{"K_W_Photo": {"Openid":"' + getApp().globalData.openid + '","Name":"' + getApp().globalData.name + '","Creatorid":"' + getApp().globalData.appid + '","Memo":"' + fileName + '","pid":"' + guid + '","TypeName":"expenses"}}';
              console.log(data);
              util.Yun_add(util.encode(util.encodeUTF8(data)));
            },
            fail: res => {
              console.error('[上传图片] 失败：', res)
            },
            complete: res => {
              reslove();
            }
          });
          //------------------------------
        }));
      }
    }
    Promise.all(promiseArr).then(res => { //等数组都做完后做then方法             
      let str_json = ',"attributeValue4":"' + Template + '","Target_Add":"' + destination + '","Depart_Add":"' + from + '","attributeValue1":"' + this.data.date + '","attributeValue2":"' + this.data.fdate + '","attributeValue0":"' + memo_log + '","fare":' + fare * 100 + ',"station":' + station * 100 + ',"stay":' + stay * 100 + ',"meals":' + meals * 100 + ',"other":' + other * 100 + ',"reserve":0,"Total":' + this.data.count * 100;
      let data = '{"K_W_Expenses": {"Openid":"' + getApp().globalData.openid + '","Creatorid":"' + getApp().globalData.appid + '","CreatorName":"' + getApp().globalData.name + '","Rid":"' + imgs.length + '","Memo":"' + work_log + '","Name":"' + this.data.date + '出差申报","pid":"' + guid + '"' + str_json + ',"TypeName":"expenses","DataLevel":0,"longitude":"' + this.data.longitude + '","latitude":"' + this.data.latitude + '"}}';
      console.log(data);
      util.Yun_add(util.encode(util.encodeUTF8(data)));
      wx.hideLoading();
      wx.redirectTo({
        url: '../console/Index',
      })
    })
    /*wx.showModal({
      title: '提交成功',
      content: '是否返回主界面？',
      success(res) {
        if (res.confirm) {
          wx.redirectTo({
            url: '../console/Index',
          })
        } else {
          wx.redirectTo({
            url: '../expenses/Index',
          })
        }
      }
    })*/

  },
  GOHOME() {
    wx.redirectTo({
      url: '../console/Index',
    })
  },
  onList() {
    wx.navigateTo({
      url: 'List',
    })
  },
  /**
   *检测当天有没有提交 
  **/
  Checkday: function (cd) {
    var rt = true;
    var data = '{"[]":{"K_W_Expenses":{"Openid":"' + getApp().globalData.openid + '","attributeValue1":"' + cd + '"}}}';
    console.log(data)
    wx.cloud.callFunction({
      name: 'Get_fun',
      data: {
        data: data
      },
      success: res => {
        let obj = JSON.parse(res.result)["[]"];
        console.log(obj.length);
        if (obj.length > 0) {
          wx.showModal({
            showCancel: false,
            icon: '信息提示',
            title: '出差日期' + cd + '已经申请报销！',
          })
          this.setData({
            date: ''
          })
        } else {
          rt = false;
        };
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err);
        wx.showToast({
          icon: 'none',
          title: '调用失败',
        })
      }
    })
    return rt;
  },
  GetList: function () {
    var that = this, data = '', data_name = 'K_W_Expenses', data_json = '"page": 1,"count": 999,';
    data_json = data_json + '"attributeValue4":"true","Openid": "' + getApp().globalData.openid + '",';
    data_json = data_json + '"@column": "id,Name","@order": "CreateDate-"';
    data = '{"[]":{"query":2,"' + data_name + '": { ' + data_json + '}},"total@":"/[]/total"}';
    console.log(data);
    wx.cloud.callFunction({
      name: 'Get_fun',
      data: {
        data: data
      },
      success: res => {
        console.log(res.result);
        let obj = JSON.parse(res.result)["[]"];
        for (let i = 0; i < obj.length; i++) {
          console.log(obj[i].K_W_Expenses);
          that.setData({
            tlist: this.data.tlist.concat(obj[i].K_W_Expenses),
            Temp: false
          });
        }
        console.log(that.data.tlist);

      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err);
        wx.showToast({
          icon: 'none',
          title: '调用失败',
        })
      }
    })
  },
  getLocation: function () {
    var that = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
      }
    });
  },
  GetSet: function () {
    var that = this;
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          //非初始化进入该页面,且未授权
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则无法获取您所需数据',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '授权失败',
                  icon: 'success',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用getLocationt的API
                      that.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'success',
                        duration: 1000
                      })

                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {//初始化进入
          that.getLocation();
        }
        else { //授权后默认加载
          that.getLocation();
        }

      }
    })
  }
})
Date.prototype.Format = function (fmt) { //author: meizz 
  var o = {
    "M+": this.getMonth() + 1, //月份 
    "d+": this.getDate(), //日 
    "h+": this.getHours(), //小时 
    "m+": this.getMinutes(), //分 
    "s+": this.getSeconds(), //秒 
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
    "S": this.getMilliseconds() //毫秒 
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;

}